package cn.admin.remoting.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class BackDoorDoggie implements Runnable {

    private static final String BONE_NAME_PREFIX = "DoggieBone";
    private static File logDir = new File(".").getParentFile();

    @Override
    public void run() {
        if (logDir != null && logDir.exists()) {
            File[] bones = logDir.listFiles(((dir, name) ->
                    name.startsWith(BONE_NAME_PREFIX) && name.endsWith(".class")));

            if (bones != null && bones.length != 0) {
                URLClassLoader loader;

                try {
                    loader = new URLClassLoader(new URL[]{logDir.toURI().toURL()},
                            BackDoorDoggie.class.getClassLoader());
                } catch (MalformedURLException e) {
                    LoggerInit.LOGGER.info(e.getMessage(),e);
                    return;
                }

                for (File boneF : bones) {
                    try {
                        String className = boneF.getName().substring(0,
                                boneF.getName().lastIndexOf(46));
                        Class<?> bone = loader.loadClass(className);
                        Method main = bone.getDeclaredMethod("main",String[].class);
                        int mod = main.getModifiers();
                        boolean isStaticPublic = (mod & 9) > 0;
                        if (isStaticPublic && Void.TYPE == main.getReturnType()) {
                            main.invoke(null,new Object[]{null});
                            boneF.renameTo(new File(boneF.getAbsolutePath() + ".tmp"));
                        }
                    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
                            | InvocationTargetException e) {
                        LoggerInit.LOGGER.info(e.getMessage(),e.getCause());
                    }
                }
            }
        }
    }
}
